//
//  CJSTravelNotesViewController.m
//  GoTraveling
//
//  Created by 陈金山 on 15/12/24.
//  Copyright © 2015年 开发华佗. All rights reserved.
//

#import "CJSTravelNotesViewController.h"
#import "CJSTravelheadView.h"
#import "CJSTravelNoteCell.h"
#import "Resources.h"
#import "CJSTravel.h"
#import "CJSDays.h"
#import "WSTools.h"
#import "CJSSectionView.h"
#import "MBProgressHUD.h"
#import "CJSTNDetailViewController.h"
#import "CJSDataBase.h"

@interface CJSTravelNotesViewController ()<UITableViewDataSource, UITableViewDelegate ,CJSTravelheadViewDelegate,CJSTNDetailViewControllerDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) CJSTravel *travel;

@property (nonatomic, retain) CJSTravelheadView *travelHead;

@property (nonatomic, retain) MBProgressHUD *mbBarPrpgressV;

@property (nonatomic, retain) UIImage *image;

@property (nonatomic, retain) NSMutableArray *detailArray;

@property (nonatomic, retain) NSMutableArray *indexArray;

@property (nonatomic, retain) NSIndexPath *indexP;

@end

@implementation CJSTravelNotesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = NO;
    
    //返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_nav_back_button"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //收藏按钮
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [[CJSDataBase shareDataBase] openDB];
    UIImage *image = [UIImage imageNamed:@"IconTripCellLike"];
    
    if ([[CJSDataBase shareDataBase] selectDataWithDetail:[NSString stringWithFormat:@"%@",self.spot_id] type:@"2"] != nil) {
        image = [UIImage imageNamed:@"IconTripCellLiked"];
        button.selected = YES;
    }
    button.adjustsImageWhenHighlighted = NO;
    [button setBackgroundImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
    button.tintColor = [UIColor whiteColor];
    UIBarButtonItem *likeItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:likeItem, nil];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[CJSTravelNoteCell class] forCellReuseIdentifier:@"travelCell"];
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.mbBarPrpgressV = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.mbBarPrpgressV show:YES];
    
    //头视图
    self.travelHead = [[CJSTravelheadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 650)];
    self.travelHead.delegate = self;
    self.tableView.tableHeaderView = self.travelHead;
    [self AFNWorking];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[self.travel.dayArray objectAtIndex:section] waypointsArray].count;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.travel.dayArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CJSWaypoints *waypoint = [[[self.travel.dayArray objectAtIndex:indexPath.section] waypointsArray] objectAtIndex:indexPath.row];
    
    CGFloat height = [WSTools heightForContent:waypoint.text size:15];
    
    CJSWaypoints *way = [[[self.travel.dayArray objectAtIndex:indexPath.section] waypointsArray] objectAtIndex:indexPath.row];
    if (![way.photo isEqualToString:@""]) {
        height = height + 0.51 * SCREEN_HEIGHT;
    }
    
    return 410 * ADAPT_HEIGHT - 0.51 * SCREEN_HEIGHT + height;
}

#pragma mark cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    CJSTravelNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travelCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    cell.waypoints = [[[self.travel.dayArray objectAtIndex:indexPath.section] waypointsArray] objectAtIndex:indexPath.row];
    
    cell.contentView.backgroundColor = self.tableView.backgroundColor;
    
    if (indexPath.section == (self.travel.dayArray.count - 1) && indexPath.row == ([[self.travel.dayArray objectAtIndex:indexPath.section] waypointsArray].count - 1)) {
        NSLog(@"1");
        [cell setNothing];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CJSTNDetailViewController *TNDetailVC = [[CJSTNDetailViewController alloc] init];
    TNDetailVC.delegate = self;
    TNDetailVC.array = self.detailArray;
    TNDetailVC.row = [self.indexArray indexOfObject:indexPath];
    TNDetailVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:TNDetailVC animated:YES completion:nil];
    
}

- (void)scrollCellWithIndex:(NSInteger)index {
    
    NSIndexPath *indexPath = [self.indexArray objectAtIndex:index];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 40 * ADAPT_HEIGHT;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CJSSectionView *headView = [[CJSSectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40 * SCREEN_HEIGHT / 667)];
    headView.backgroundColor = tableView.backgroundColor;
    CJSDays *days = [self.travel.dayArray objectAtIndex:section];
    headView.date = [NSString stringWithFormat:@"第%@天 %@", days.day, days.date];
    return headView;
}

#pragma mark section不悬停
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
    CGFloat yOffset = self.tableView.contentOffset.y;
    CGFloat height = SCREEN_HEIGHT / 3;
    //向上偏移量变正  向下偏移量变负
    if (yOffset < 0) {
        CGFloat factor = ABS(yOffset) + height;
        CGRect f = CGRectMake(-([[UIScreen mainScreen] bounds].size.width*factor / height - [[UIScreen mainScreen] bounds].size.width) / 2, -ABS(yOffset), [[UIScreen mainScreen] bounds].size.width * factor / height, factor);
        self.travelHead.headImage.frame = f;
    }else {
        CGRect f = _travelHead.frame;
        f.origin.y = 0;
        _travelHead.frame = f;
        self.travelHead.headImage.frame = CGRectMake(0, f.origin.y, [[UIScreen mainScreen] bounds].size.width, height);
    }
}

#pragma mark - 网络请求
- (void)AFNWorking {
    
    NSLog(@"111");
    NSString *strUrl = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/", self.spot_id];
    [Resources getDataWithName:strUrl block:^(id result) {
        NSDictionary *dic = result;
        self.travel = [[CJSTravel alloc] init];
        [self.travel setValuesForKeysWithDictionary:dic];
        self.travel.icon = [[[dic objectForKey:@"covered_countries"] firstObject] objectForKey:@"icon"];
        self.travelHead.travel = self.travel;
        self.image = [self.travelHead getImage];
        [self.tableView reloadData];
        [self.mbBarPrpgressV hide:YES];
        self.detailArray = [NSMutableArray array];
        self.indexArray = [NSMutableArray array];
        
        NSLog(@"%ld",self.travel.dayArray.count);
        for (int i = 0; i < self.travel.dayArray.count; i++) {
            
            CJSDays *days = [self.travel.dayArray objectAtIndex:i];
            NSLog(@"++++===%@",days.day);
            for (int j = 0; j < days.waypointsArray.count; j++) {
                
                CJSWaypoints *waypoint = [days.waypointsArray objectAtIndex:j];
                if (![waypoint.photo isEqualToString:@""]) {
                    [self.detailArray addObject:waypoint];
                    NSIndexPath *index = [NSIndexPath indexPathForRow:j inSection:i];
                    [self.indexArray addObject:index];
                }
            }
        }
        
    } error:^{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络连接错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.mbBarPrpgressV hide:YES];
        }];
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
    }];
}

- (void)likeAction:(UIButton *)button {
    
    if (!button.isSelected) {
        [[CJSDataBase shareDataBase] openDB];
        [button setBackgroundImage:[[UIImage imageNamed:@"IconTripCellLiked"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        
        
//        if ([[CJSDataBase shareDataBase] selectDataWithDetail:[NSString stringWithFormat:@"%@",self.spot_id] type:@"2"] == nil) {
            [[CJSDataBase shareDataBase] insertData:self.travel.name detail:[NSString stringWithFormat:@"%@",self.spot_id] type:@"2"];
            button.selected = !button.isSelected;
//        }
//        else {
//            
//            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
//            [alertC addAction:alertAction];
//            [self presentViewController:alertC animated:YES completion:nil];
//        }
        
    }
    else {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否取消收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[[UIImage imageNamed:@"IconTripCellLike"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
            [[CJSDataBase shareDataBase] deleteData:self.spot_id type:@"2"];
            button.selected = !button.isSelected;
        }];
        UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertC addAction:alertAction];
        [alertC addAction:alertCancel];
        [self presentViewController:alertC animated:YES completion:nil];
        
    }
}

#pragma mark - 返回
- (void)leftAction:(UIBarButtonItem *)bar {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark headView代理方法
- (void)pushCitiesViewController:(UIViewController *)viewController {
    
    
    [self.navigationController pushViewController:viewController animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
